import { useLocation } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { routeList } from '@/router/index.jsx';
import useMatchRouteRule from '@/hooks/useMatchRouteRule.js';
import { INDEX_ROUTE } from '@/constants/pageConstant.js';

export function useMatchRoute() {
  // 获取所有路由
  const routes = routeList;
  // 获取当前url
  const location = useLocation();
  // 获取当前路由规则
  const routeRule = useMatchRouteRule();
  // 匹配到的路由信息
  const [matchRoute, setMatchRoute] = useState(null);

  // 获取路由数据
  function getRouteData(itemPath, list, fatherPath) {
    let data = {};
    for (let i = 0; i < list.length; i++) {
      const item = list[i];
      const path = fatherPath ? fatherPath + '/' + item.path : item.path;
      if (!path?.startsWith(INDEX_ROUTE)) {
        continue;
      }
      // 替换"?"的原因是无法匹配可选路由
      if (path.replace('?', '') === itemPath.replace('?', '')) {
        data = {
          ...item,
          path
        };
        break;
      }
      if (Array.isArray(item.children)) {
        const routeData = getRouteData(itemPath, item.children, path);
        if (Object.keys(routeData).length > 0) {
          data = routeData;
          break;
        }
      }
    }
    return data;
  }

  // 监听pathname变了，说明路由有变化，重新匹配，返回新路由信息
  useEffect(() => {
    if (!routeRule) return;
    const route = getRouteData(routeRule, routes);
    setMatchRoute({
      title: route.label ?? '未找到页面标题',
      pathname: location.pathname,
      children: route.element,
      routeRule: routeRule
    });
  }, [location.pathname, routeRule]);

  return matchRoute;
}
